import React, { useEffect, useState } from 'react';
import cx from 'classnames';
import WPT from 'wpt';

import EmptyData from 'components/EmptyData';
import { needExposure } from 'modules/exposureLogic';
import GoodsWall from 'modules/goodsWall/v2';
import SaleItem, { mergeVideoCover } from 'modules/SaleItem';
import LiveItem from 'views/category/ListItem/homePage';

import S from './index.less';

// 无限推荐
const isLimitless = (url = '', param = {}) => {
    // 不是小场景推荐接口
    if (!url.includes('common-scene')) {
        return false;
    }
    const type = WPT.Util.query(WPT.Util.urlAddQuery(url, param)).type;
    return (
        [
            'user_center', // 买家中心
            'orderdetail', // 订单详情
            'orderlist', // 订单列表、查看评价、评价成功
            'participate', // 参拍
            'paid', // 支付完成
            'footmark', // 足迹
            'logistics', // 物流详情
            'shop_detail', // 店铺详情
            'sale_detail', // 普通拍品详情
            'search_scene', // 搜索
            'collection', // 围观
        ].includes(type) && type
    );
};

const RecommandHead = ({ text = '你可能还喜欢', className }) => (
    <div className={cx(S.recommandHead, className)}>{text}</div>
);

export function linkParams(props) {
    const r = $.isFunction(props.r) ? props.r(props) : props.r;
    const params = {
        r,
        ...(props.c ? { c: props.c } : {}),
        ...(props.fromPageName ? { fromPageName: props.fromPageName } : {}),
    };
    if (props.pos || props.dataType) {
        params.pos = [props.pos, props.dataType].filter((i) => i).join('_');
    }
    return params;
}

const ScrollTop = ({ showScrollTop = false, sessionKey = '__wpt_scroll_top' }) => {
    const [show, setShow] = useState(showScrollTop && !WPT.localStorage.getItem(sessionKey));

    useEffect(() => {
        let key = WPT.Util.uuid();
        let timeout = null;
        if (show) {
            timeout = setTimeout(() => {
                WPT.scroll.appendScroll(key, () => {
                    setShow(false);

                    WPT.localStorage.setItem(sessionKey, 1);
                    WPT.scroll.clear(key);
                });
            }, 500);
        }
        return () => {
            WPT.scroll.clear(key);
            clearTimeout(timeout);
        };
    }, []);

    return (
        !!showScrollTop &&
        !WPT.localStorage.getItem(sessionKey) && (
            <div className={cx(S.scrollTop, !show && S.hide)}>
                向上滑浏览更多拍品
                <i className={cx(S.arrowTop)} />
            </div>
        )
    );
};

export default class RecommandGoods extends React.PureComponent {
    static theme = {
        gray: S.gray,
        white: S.white,
    };

    static defaultProps = {
        api: '/v1.0/discovery/get-guess-data?num=6',
        params: {},
        children: '',
        r: '',
        c: '',
        pos: '',
        inited: false,
        newFoot: true,
        noMore: false, // 如果接口没数据，那么不展示模块
        needExposure: false, // 是否需要曝光
        exposureId: '',
        saleExposureId: '',
        preHandleData: undefined,
        theme: RecommandGoods.theme.gray,
        className: '',
        // 图墙无限加载
        limitless: false,

        // 以下字段上报用
        reportType: '',
        extendHrefQuery: {},
        extendExposureData: {},
    };

    state = {
        list: [], // 老板样式列表
    };

    componentDidMount() {
        const { limitless, api, params } = this.props;
        !limitless && !isLimitless(api, params) && this.getData();
    }

    getData() {
        const { params, preHandleData } = this.props;
        const postDate = { screen: `${window.innerWidth}_${window.innerHeight}`, ...params };
        WPT.getData(WPT.Util.handleApi(this.props.api), postDate, ({ code, msg, data }) => {
            preHandleData && (data = preHandleData(data));
            if (code == 0) {
                this.setState({
                    list: data.list || data.items,
                    ...data,
                    inited: true,
                });
            } else {
                WPT.Modal.tips(msg);
            }
            return false;
        });
    }

    getLazyImageProps4Sale = (item, position) =>
        !!this.props.needExposure && {
            src: item.img || item.cover,
            hasBlur: true,
            exposureData: this.exposureAuth({ item }) && {
                uri: item.uri,
                category: item.category,
                secCategory: item.secCategory,
                currPrice: item.nowPrice || item.startPrice,
                ...(item.bidCount ? { bidCount: item.bidCount } : {}),
                ...(item.rTime ? { isRecommend: true } : {}),
                remainMins: Math.floor((item.etime - WPT.nowTime) / 60),
                shopUri: item.shopUri || item.sellerUri,
                ...(item.goodshop ? { goodshop: item.goodshop } : {}),
                ...(item.attr ? { attr: item.attr } : {}),
                type: this.props.reportType,
                ...(this.props.saleExposureId && { id: this.props.saleExposureId }),
                ...this.getExtendExposureData(item, position),
            },
            quickUp: item.quickUp,
            router: WPT.curRouter,
            goodsList: true,
        };

    goodsWallTemp = (props) => (
        <>
            <ScrollTop showScrollTop={!props.isNoData && this.props.showScroll} />
            {this.renderList(props)}
        </>
    );

    // 判断是否可以曝光
    exposureAuth = ({ item }) => {
        const { needExposure: ne } = this.props;
        if (typeof ne === 'boolean') {
            return ne && needExposure(item);
        } else if (typeof ne === 'function') {
            // 交给外层去控制是否曝光
            return ne(item);
        }

        return false;
    };

    getExtendExposureData = (item, index) => {
        const { extendExposureData } = this.props;
        if (WPT.Util.getType(extendExposureData) === 'object') {
            return extendExposureData;
        } else if (WPT.Util.getType(extendExposureData) === 'function') {
            return extendExposureData(item, index);
        }
        return {};
    };

    // 拼接需要带在链接上的参数
    getExtendHrefQuery = (item, index) => {
        const { extendHrefQuery } = this.props;
        let query = {};

        if (WPT.Util.getType(extendHrefQuery) === 'object') {
            query = extendHrefQuery;
        } else if (WPT.Util.getType(extendHrefQuery) === 'function') {
            query = extendHrefQuery(item, index);
        }

        return query;
    };

    renderGoodsWall = () => (
        <GoodsWall
            className={S.recommendGoods}
            ajaxUrl={WPT.Util.handleApi(this.props.api)}
            ajaxParam={{
                screen: `${window.innerWidth}_${window.innerHeight}`,
                isNew: true,
                ...this.props.params,
            }}
            templates={this.goodsWallTemp}
            skeletonClass={S.recommendSkeleton}
            skeleton
        />
    );

    renderList = ({ items: list = [], isNoData }) => {
        const { noMore, newFoot, exposureId } = this.props;
        return (
            <>
                <div className={S.list}>
                    {list &&
                        !$.isEmptyObject(list) &&
                        list.map((item, index) =>
                            item.isShowLive ? (
                                <LiveItem
                                    {...linkParams({ dataType: item.dataType, ...this.props })}
                                    key={index}
                                    className={cx(S.liveItem, 'c6y')}
                                    item={item.isShowLive}
                                    needReport={this.exposureAuth({ item: item.isShowLive })}
                                    newFoot={newFoot}
                                    theme={!!item.isShowLive.liveGroup && 'hemai'}
                                    exposureId={exposureId}
                                    newLazy
                                    extendHrefQuery={this.getExtendHrefQuery(item.isShowLive, index)}
                                    extendExposureData={this.getExtendExposureData(item.isShowLive, index)}
                                />
                            ) : (
                                <SaleItem
                                    key={`${item.uri}-${index}`}
                                    className={cx(S.saleItem)}
                                    item={{
                                        img: item.cover,
                                        ...item,
                                    }}
                                    lazyImageProps={this.getLazyImageProps4Sale(item, index)}
                                    href={WPT.Util.urlAddQuery(`/uri/${item.uri}`, {
                                        ...linkParams({ dataType: item.dataType, ...this.props }),
                                        ...(item.token && { mt: item.token }),
                                        ...(item.attr && { attr: JSON.stringify(item.attr) }),
                                        ...mergeVideoCover(item),
                                        ...this.getExtendHrefQuery(item, index),
                                    })}
                                    newLazy
                                />
                            )
                        )}
                </div>
                {noMore && !$.isEmptyObject(list) && <div className={S.endHint}>没有更多了</div>}
                {isNoData && <EmptyData title="暂无更多拍品" imageSrc={EmptyData.imageType.good} fixedHeight={false} />}
            </>
        );
    };

    render() {
        const { list, inited } = this.state;
        const { noMore, className, title = undefined, theme, headClassName, limitless } = this.props;

        if (WPT.os.dyXcx) {
            return null;
        }

        if (noMore && $.isEmptyObject(list)) {
            return null;
        }

        return (
            <div className={cx(theme)}>
                <div className={S.title}>
                    {this.props.children || <RecommandHead text={title} className={headClassName} />}
                </div>
                <div className={cx(S.wrap, className)}>
                    {limitless || isLimitless(this.props.api, this.props.params)
                        ? this.renderGoodsWall()
                        : this.renderList({
                              isNoData: inited && $.isEmptyObject(list),
                              items: list,
                          })}
                </div>
            </div>
        );
    }
}
